
import React, { Component } from 'react';
import {
  StyleSheet, Text, FlatList, Alert,
  PixelRatio, View, Image, TouchableOpacity, DeviceEventEmitter, Animated
} from "react-native";
import { API, API_GENERATE } from '../../../../config/api';
import { GLOBAL } from '../../../../config/global';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import HTTP from '../../../../utils/http';
import { NavigationEvents } from 'react-navigation';
import ToastUtil from '../../../../utils/toast';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import { CommonDialog } from '../../../../components/common/Dialog';
import OrderDetailsService from '../../details/_common/service';
import { ProgressModal } from '../../../../components/common/ProgressModal';
// import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import { ListPageComponent } from '../_component/listPage';
import { NewAccountHome } from '../../../../components/common/newAccountHome';
import { SlideSelect } from '../../../../components/common/slideSelect';


const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../../imgs/order/down.png')
const modalPicDelCfg = {
  visible: false,
  uri: null,
  delPress: () => { },
  picPress: () => { }
}

const LIST = [
  {
    key: 'P',
    label: '采购长约',
  },
  {
    key: 'S',
    label: '销售长约',
  },
]
export class LongFramePage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '长约框架审批',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center',
      }
    }
  };

  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      tabIndex: 0,
      companyIndex: 0,
      tabItem: 0,
      status: 'data',
      refreshIcon: false,
      listData: [],
      listItemData: {},
      listItemCount: {},
      itemData: {},
      isTablet: true,
      cntList: true,
      isDataItem: true,
      itemAuditingletedCnt: '0',
      itemAuditRejectCntCnt: '0',
      totalPage: '0',
      dataList: '',
      previewModalVisible: false,
      lightBoxData: {
        modalVisible: false,
        onClosePress: this._closeLightBox,
        title: '',
        rowDataList: [],
        status: 'data',
        refreshIcon: false,
      },
      showRejectModal: false,
      alertShow: false,
      options: [],
      choice: {}
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1;
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
      orderType: 'P',
    }
    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
        previewModalVisible: false,
      });
    }
    this.mackStr = '';
  }

  async componentDidMount() {
    await this.getSorage();
    await this.initPage();
    await this.init();
    await this.inits()
  }

  //获取业务组织
  async getSorage() {
    let resall = await HTTP.POST(API_GENERATE(API.LONG_FRNE_LIST_MUL))
    let options = resall || []
    options.map(item => {
      item.rowCount = item.paginationModel.recordCount
    })
    this.setState({
      options
    })
  }

  //初始化数据
  initPage = async (refreshIcon) => {
    let { companyIndex, options } = this.state;
    let { corpId } = options[companyIndex] || {};
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    this.params = {
      pageNo: this.pageParams.pageNo,
      pageSize: this.pageParams.pageSize,
      orderType: this.pageParams.orderType,
      corpId: corpId || ''
    }
    let res = await HTTP.POST(API_GENERATE(API.LONG_FRNE_LIST), this.params)
    if (res) {
      let responseData = res.rows;
      this.setState({
        listData: this.pageParams.pageNo == '1' ? responseData : this.state.listData.concat(responseData),
        status: responseData.length > 0 ? 'data' : 'empty',
        refreshIcon: false,
        totalPage: res.totalPage,
        choice: options[companyIndex] || {}
      })
      this.pageParams.pageNo = res.pageNo++;
    } else {
      this.setState({
        status: 'error'
      })
    }
  }


  init = async (refreshIcon) => {
    // this.setState({
    //   status: this.reload ? 'loading' : 'data',
    //   refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    // })
    let { companyIndex, options } = this.state;
    let { corpId } = options[companyIndex] || {};
    this.params = {
      pageNo: this.pageParams.pageNo,
      pageSize: this.pageParams.pageSize,
      orderType: 'S',
      corpId: corpId || ''
    }
    let res = await HTTP.POST(API_GENERATE(API.LONG_FRNE_LIST), this.params)
    if (res) {
      this.setState({
        listItemCount: res,
        status: res ? 'data' : 'empty',
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  inits = async (refreshIcon) => {
    // this.setState({
    //   status: this.reload ? 'loading' : 'data',
    //   refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    // })
    let { companyIndex, options } = this.state;
    let { corpId } = options[companyIndex] || {};
    this.params = {
      pageNo: this.pageParams.pageNo,
      pageSize: this.pageParams.pageSize,
      orderType: 'P',
      corpId: corpId || ''
    }
    let res = await HTTP.POST(API_GENERATE(API.LONG_FRNE_LIST), this.params)
    if (res) {
      this.setState({
        listItemData: res,
        status: res ? 'data' : 'empty',
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  loadMore = () => {
    if (this.state.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  refresh = () => {
    this.pageParams.pageNo = 1;
    if (this.state.totalPage >= this.pageParams.pageNo) {
      this.reload = false;
      this.getSorage()
      this.initPage();
      this.init();
      this.inits();
    }
  }

  _tabFn = (items, tabIndex,) => {
    if (tabIndex == 0) {
      this.pageParams.orderType = 'P';
    } else {
      this.pageParams.orderType = 'S';
    }

    this.setState({
      tabIndex,
      params: {
        status: items.key
      },
      totalPage: '0',
    }, () => {
      this.pageParams.pageNo = 1;
      this.totalPage = 0;
      this.initPage();
    })
  }

  onErrorRefresh = () => {
    let { tabIndex } = this.state;
    if (tabIndex != 2) {
      this.initPage();
    }
  }
  // 查看审批流
  _getCheckApprove = async (item) => {
    const { choice } = this.state;
    const { corpId } = choice || {};
    // this.setState({ status: 'loading' })
    //查询审批节点

    let responseData1 = await OrderDetailsService.checkApproval(item.businessKey, '18', item.processInstanceId, corpId);
    responseData1 = responseData1 && responseData1.map((item) => {
      if (item.auditResult == 9) {
        item.auditResultName = '操作';
      }
      return item;
    })
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = true;
    lightBoxData.title = '审批状态';
    lightBoxData.rowDataList = responseData1;
    this.setState({
      lightBoxData,
      status: 'data'
    })
  }
  _closeLightBox = () => {
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = false;
    this.setState({ lightBoxData });
  }
  // 查看框架
  goItemFrame = (item) => {
    let orderType = this.pageParams.orderType;
    this.props.navigation.navigate('LongOrderDetailPage', { pramasData: item.orderInfo, orderType, choice: this.state.choice })
  }

  // 同意
  consentCreate = (item) => {
    item.auditResult = 1;
    item.remark = '';
    this.setState({
      showRejectModal: true,
      itemData: item,
    })
  }

  // 驳回 
  consentRenew = (item) => {
    item.auditResult = 0;
    item.remark = '';
    if (item) {
      this.setState({
        showRejectModal: true,
        itemData: item,
      })
    } else {
      ToastUtil.showWarning('没有数据')
    }
  }

  // 审批
  approve = async (remark) => {
    const data = this.state.itemData;
    let requestParams = {
      businessKey: data.businessKey,
      formKey: data.formKey,
      remark,
      // taskName: data.taskName,
      taskId: data.taskId,
      auditResult: data.auditResult,
      corpId: this.state.choice.corpId || ''
    };
    let text = requestParams.auditResult ? '审批' : '驳回';
    this.setState({
      showRejectModal: false,
      status: 'loading'
    })
    let res = await HTTP.POST(API_GENERATE(API.LONG_DEAL_AUDIT), requestParams);
    console.log('sss', res)
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.reloadPage()
      })
    } else {
      this.setState({
        status: 'data'
      })
    }
  }


  reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.setState({
      status: 'loading'
    })
    this.getSorage()
    this.initPage();
    this.inits();
    this.init();
  }

  _approvalListItim = (data) => {

    this.listMethodData = {
      item: data.item,
      orderType: this.pageParams.orderType,
      onGetCheckApprove: this._getCheckApprove, // 审批流
      onConsentCreate: this.consentCreate, // 同意审批
      onGoItemFrame: this.goItemFrame, // 查看框架
      onConsentRenew: this.consentRenew, // 
      choice: this.state.choice
    }

    return <ListPageComponent {...this.listMethodData} />
  }

  render() {
    let { tabIndex, listData, refreshIcon, status, showRejectModal, modalVisible, listItemData, listItemCount } = this.state;
    let { lightBoxData, alertShow, choice, options, itemData } = this.state || {};

    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={async () => {
          await this.getSorage();
          this.initPage();
          this.init();
          this.inits();
        }} />
        {options.length > 1 ?
          <NewAccountHome
            fn={(val) => {
              this.setState({ companyIndex: val }, () => {
                this.pageParams.pageNo = '1';
                this.getSorage()
                this.initPage();
                this.init();
                this.inits();
              })
            }}
            options={options}
            choice={choice} />
          : null}
        <View style={styles.headBox}>
          {LIST.map((items, index) => {
            return (
              <TouchableOpacity activeOpacity={1} onPress={() => { this._tabFn(items, index) }}
                key={index}
                style={[styles.tabItem, this.state.tabIndex == index ? { backgroundColor: style.color.themeColor } : { backgroundColor: 'transparent' }]}>
                <Text style={[styles.tabText, this.state.tabIndex == index ? { color: '#fff' } : { color: style.color.themeColor }]}> {items.label}</Text>
                {index == 0 && listItemData.recordCount || index == 1 && listItemCount.recordCount ?
                  <View style={[styles.numPoint, this.state.tabIndex == index ? { backgroundColor: '#fff' } : { backgroundColor: 'red' }]}></View>
                  : null
                }
              </TouchableOpacity>
              // <Text key={index} 
              // onPress={() => { this._tabFn(items, index) }} 
              // style={[styles.tabItems, tabIndex == index ? styles.tabItemActive : null]}>
              //   {items.label} {index == 0 ? listItemData.recordCount : listItemCount.recordCount} </Text>
            )
          })
          }
        </View>
        {
          status == 'data' ? (
            (
              <View style={styles.body}>
                <FlatList
                  data={listData}
                  renderItem={
                    this._approvalListItim
                  }
                  refreshing={refreshIcon}
                  onRefresh={() => { this.refresh() }}
                  onEndReachedThreshold={1}
                  onEndReached={() => { this.loadMore() }}
                />
              </View>
            )
          ) : (<View style={{ flex: 1 }}>
            <PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />
          </View>)
        }
        <RefuseModal
          titleText={'审批意见'}
          placeholderText={itemData.auditResult ? '请输入同意原因' : null}
          propsDefaultValue={itemData.auditResult ? '审批同意' : '审批驳回'}
          visible={showRejectModal}
          btnPress={(text) => {
            this.approve(text)
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
        {/* 审批流 */}
        <ProgressModal {...lightBoxData} />

        {options.length ? <SlideSelect alertShow={alertShow} options={options}
          select={(val) => {
            this.setState({ choice: val || options[0], alertShow: false }, () => {
              this.reloadPage();
            })
          }}
          unselect={() => {
            this.setState({ alertShow: false })
          }} /> : null}
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  headBox: {
    backgroundColor: style.color.bgGray,
    flexDirection: 'row',
    alignItems: 'center',
    paddingTop: 10,
    paddingBottom: 10
  },
  stateView: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    backgroundColor: style.color.themeColor,
  },
  stateItem: {
    // paddingTop: 10 * scale,
    // paddingBottom: 10 * scale,
    // paddingLeft: 10 * scale,
    // paddingRight: 10 * scale,
    padding: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 20 * scale,
    marginRight: 10 * scale,
    flexDirection: 'row'
  },
  stateItemText: {
    paddingLeft: 2 * scale,
    paddingRight: 2 * scale,
    fontSize: 11 * scale,
    color: style.color.themeColor,
    fontWeight: '500',
  },
  stateItemInfo: {
    width: 5 * scale,
    height: 5 * scale,
    backgroundColor: style.color.fontRed1,
    borderRadius: 3 * scale,
    position: 'relative',
    top: -5 * scale
  },
  stateItemActive: {
    backgroundColor: style.color.themeColor,
  },
  stateActive: {
    backgroundColor: style.color.white,
  },
  stateItemTextActive: {
    fontSize: 11 * scale,
    color: style.color.white
  },
  stateItemInfoActive: {
    backgroundColor: style.color.white
  },
  body: {
    flex: 1,
    backgroundColor: style.color.bgGray
  },
  itemLightText: {
    fontSize: 12 * scale,
    color: '#272727',
    fontWeight: '500',
  },
  itemTimeData: {
    marginBottom: 7 * scale,
    flexDirection: 'row',
    paddingLeft: 12 * scale,
    paddingRight: 0
    // justifyContent: 'flex-end',
  },
  itemLightName: {
    justifyContent: 'flex-start',
  },
  itemAccount: {
    fontSize: 12 * scale,
    color: '#272727',
  },
  itemDayTime: {
    // justifyContent: 'flex-end',
    flexDirection: 'row',
    position: 'relative',
    alignItems: 'center',
    paddingLeft: 12 * scale,
    // flex: 1,
  },
  consent: {
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    fontSize: 12 * scale,
    opacity: 1,
    color: '#ffffff',
    alignItems: 'center',
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    // marginRight: 0 * scale,
    flexDirection: 'row',
    backgroundColor: style.color.themeColor,
    overflow: 'hidden'
  },
  consentColor: {
    // backgroundColor: style.color.themeColor,
  },
  itemdown: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    alignItems: 'center',
    paddingRight: 20 * scale,
    paddingLeft: 20 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    borderWidth: 1 * scale,
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    borderRadius: 15 * scale,
    marginRight: 20 * scale,
    flexDirection: 'row',
    marginLeft: 10 * scale,
  },
  itemTime: {
    flexDirection: 'row',
    flex: 1,

  },
  itemWrap: {
    backgroundColor: '#fff',
    width: '100%',
    borderRadius: 8 * scale,
    marginTop: 6 * scale,
    // paddingLeft: 12 * scale,
    // paddingRight: 12 * scale,
    // paddingBottom: 14 * scale,
    paddingTop: 14 * scale,
  },
  itemType: {
    // flex: 4
  },
  itemLightColor: {
    // justifyContent: 'flex-end',
    fontSize: 12 * scale,

    marginRight: 10 * scale,
    color: style.color.themeColor,
    fontWeight: '500',
  },
  itemLightText: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '500',
  },
  itemBorder: {
    height: 1 * scale,
    backgroundColor: '#E3E7F0',
    marginBottom: 15 * scale,
  },
  itemName: {
    flexDirection: 'row',
    marginBottom: 10 * scale,
    // marginTop: 5 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  itemTypeName: {
    color: '#ffffff',
    padding: 3 * scale,
    backgroundColor: style.color.themeColor,
    fontSize: 12 * scale,
    fontWeight: '500',
  },
  itemContent: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'relative',
    marginBottom: 15 * scale,
    paddingLeft: 12 * scale,
  },
  itemContentRemark: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'relative',
    marginBottom: 12 * scale,
    paddingLeft: 12 * scale,
    paddingTop: 20 * scale,
  },
  itemContractNumber: {
    color: '#000000',
    fontSize: 12 * scale,
    flex: 4,
  },
  itemContractName: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600',
    flex: 4
  },
  ItemRemarks: {
    color: '#000000',
    fontSize: 12 * scale,
    flex: 2
  },
  itemArrowIcon: {
    flexDirection: 'row',
    position: 'relative',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#000000'
  },
  arrowIcon: {

    justifyContent: 'center',
  },
  itemApplyAmount: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    paddingRight: 10 * scale,
  },
  itemNumber: {
    color: '#000000',
    fontSize: 12 * scale,
    fontWeight: '600',
    flex: 2,
    color: '#0087FF'
  },
  itemApprovalFlow: {
    justifyContent: 'flex-start',
    flex: 3, color: '#0087FF',
    fontWeight: '600'
  },
  textRow: {
    marginBottom: 20 * scale
  },
  textRowText: {
    paddingLeft: 15 * scale
  },
  moreInner: {
    width: 13 * scale,
    height: 13 * scale,
    transform: [{ rotate: '0deg' }],
    // tintColor: '#fff'
  },
  more: {
    padding: 15 * scale,
    flexDirection: 'row',
    position: 'relative',
    alignItems: 'center',
    justifyContent: 'center',
    // backgroundColor: '#000000'
  },
  itemBody: {
    position: 'relative',
    overflow: 'hidden'
  },
  goodsItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 7 * scale,
    marginBottom: 8 * scale,
    height: 40 * scale
  },
  accountSelect: {
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center'
  },
  tabItem: {
    // flex:1,
    paddingTop: 5 * scale,
    paddingBottom: 5 * scale,
    paddingLeft: 16 * scale,
    paddingRight: 16 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    marginHorizontal: 10,
    borderWidth: 1,
    borderRadius: 20,
    borderColor: style.color.themeColor
  },
  tabText: {
    color: '#fff'
  },
  numPoint: { backgroundColor: '#fff', width: 5, height: 5, position: 'absolute', borderRadius: 16, right: 10, top: 5 }
})